package com.taoz.mianshiwa.helper;

import cn.dev33.satoken.stp.StpUtil;
import com.taoz.mianshiwa.common.ErrorCode;
import com.taoz.mianshiwa.constant.RedisConstant;
import com.taoz.mianshiwa.exception.BusinessException;
import com.taoz.mianshiwa.exception.ThrowUtils;
import com.taoz.mianshiwa.model.entity.User;
import com.taoz.mianshiwa.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CrawlerDetectHelper {
    @Resource
    private CounterHelper counterHelper;
    @Resource
    private UserService userService;

    // 将该用户的访问次数统计，过于频繁执行对应操作
    public void detectCrawlerByCount(long loginUserId) {
        // 设置界限
        final int WARN_COUNT = 10;
        final int BAN_COUNT = 20;

        // 统计次数
        String key = RedisConstant.getUserAccessKey(loginUserId);
        long count = counterHelper.incrAndGet(key);

        // 60s访问超过20次进行封禁
        if (count > 20) {
            // 进行封号处理
            User user = new User();
            user.setId(loginUserId);
            user.setUserRole("ban");
            userService.updateById(user);
            // 踢下线
            StpUtil.kickout(loginUserId);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "访问过于频繁，用户被封禁");
        }

        if (count == 10) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "访问过于频繁");
        }
    }
}
